import Taro,{ Component,Config } from "@tarojs/taro";
import { View,ScrollView } from "@tarojs/components";
import { AtCard,AtActivityIndicator,AtMessage,AtLoadMore   } from "taro-ui";
import moment from "moment";
import Utils  from "../../utils/index";
import './index.scss';

//统一返回数据格式
interface RetuValue {
  result:string,
  code:number,
  msg:string,
  showMsg:string,
}
//列表数据展示
interface ItemLIstInter {
  title:string,  //标题
  id:number,  //主键id
  create_at:string,  //创建时间
  author:{
    avatar_url:string,
    loginname:string,
  },  //作者
  tab:string,  //类型 分享 问答
  top:string,  //置顶
}
export default class CNode extends Component {
  config:Config = {
    navigationBarTitleText:'cNode',
  }
  state = {
    windowHeight:100,
    Item:[],
    status:'noMore',  //3-没有更多数据,2-加载中 1-加载完毕
  }
  onScrollToUpper(event){
    console.log(event,'滚动到顶部');
    Taro.atMessage({
      'message':'加载数据中...',
      'type':'info',
    })
    this.getList().then(res=>{
      console.log(res,'获取数据');
      this.setState({
        Item:res,
      })
      Taro.atMessage({
        'message':'加载最新数据成功',
        'type':'success',
      })
    })
  }
  onScrollToLower(){
   this._getLoadingMore(); 
  }
  _getLoadingMore = ()=>{
    console.log('滚动到底部');
    this.setState({
      status:'loading'
    })
    this.getList().then((res:Array<number>)=>{
      if(res.length>=20){
        let value = this.state.Item.concat(res);
        this.setState({
          Item:value,
          status:'more',
        })
      }else{
        this.setState({
          status:'noMore',
        })
      }
      console.log(res,'获取数据');
    })
  }
  componentWillMount(): void {
    const _this = this;
    //获取设备高度
   Taro.getSystemInfo({
     success: function(res) {
        _this.setState({
          windowHeight:res.windowHeight
        })
       }
   })
    this.getList().then(res=>{
      console.log(res,'获取数据');
      this.setState({
        Item:res,
      })
    })
  }
  getTime = (val)=>{
    let value = moment(val).format("YYYY-MM-DD HH:mm:ss");
    return String(Utils.getTime(value));
  }
  //获取列表数据
  getList = (page=1,limit=20)=>{
    return new Promise((resolve,reject)=>{
      Taro.cloud.callFunction({
        name:'https',
        data:{
          url:`https://cnodejs.org/api/v1/topics?page=${page}&limit=${limit}`,
        }
      }).then((res:RetuValue)=>{
        let value = JSON.parse(res.result);
        resolve(value.data);
      }).catch(err=>{
        reject(err);
      })
    })
  }
  openDetails = (id)=>{
    Taro.navigateTo({
      url:'/pages/cnode/details/index?id='+id,
    })
  }
  handleClick = ()=>{
     this._getLoadingMore(); 
  }
  render(){
    let ItemList: JSX.Element [] | JSX.Element;
    const value = this.state.Item;
    const height = this.state.windowHeight;
    const scrollStyle = {
      height: height+'px'
    }
    const scrollTop = 0
    const Threshold = 20
    if(value.length>0){
      ItemList = value.map((item:ItemLIstInter,index:number)=>{
        return (
          <View key={index} onClick={()=>{this.openDetails(item.id)}}>
            <View className='AtCardView'>
              <AtCard
                note={this.getTime(item.create_at)}
                extra={item.top?'置顶':item.tab == "share"?'分享':'问答'}
                title={item.author.loginname}
                thumb={item.author.avatar_url}
              >
                {item.title}
              </AtCard>
            </View>
            <View className='middle'></View>
          </View>
        )
      })
    }
    return (
      <ScrollView
        scrollY
        scrollWithAnimation
        scrollTop={scrollTop}
        style={scrollStyle}
        lowerThreshold={Threshold}
        upperThreshold={Threshold}
        onScrollToUpper={this.onScrollToUpper}
        onScrollToLower={this.onScrollToLower}
      >
        { value.length>0?
          <View>
          {ItemList}
          <AtLoadMore
          onClick={this.handleClick.bind(this)}
          status={this.state.status}
        />
          </View>
          :
          <AtActivityIndicator mode='center' content='加载中...'></AtActivityIndicator>
        }
        <AtMessage></AtMessage>
      </ScrollView>
    )
  }
}
